package org.javers.spring.boot

import org.javers.core.Javers
import org.javers.spring.boot.sql.DummyEntityRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.transaction.annotation.Transactional
import spock.lang.Specification

import static org.javers.repository.jql.QueryBuilder.byInstanceId

@Transactional
abstract class SpringBootAuditableIntegrationBaseTest extends Specification {

    @Autowired
    Javers javers

    @Autowired
    DummyEntityRepository dummyEntityRepository

    @Autowired
    EmployeeRepository employeeRepository

    @Autowired
    EmployeeRepositoryWithJavers employeeRepositoryWithJavers

    def "@JaversSpringDataAuditable aspect should work effortlessly with spring-boot"(){
        given:
        def entity = DummyEntity.random()
        entity.name = "a"

        def persistedEntity = dummyEntityRepository.save(entity)
        assert dummyEntityRepository.getOne(persistedEntity.id).name == "a"

        persistedEntity.name = "b"
        persistedEntity = dummyEntityRepository.saveAndFlush(persistedEntity)
        assert dummyEntityRepository.getOne(persistedEntity.id).name == "b"

        when:
        def snapshots = javers.findSnapshots( byInstanceId(persistedEntity.id, DummyEntity).build() )

        then:
        snapshots.size() == 2
        snapshots[0].getPropertyValue("name") == "b"
        snapshots[1].getPropertyValue("name") == "a"
    }

    def "@JaversSpringDataAuditable aspect should work when Ids are generated by Hibernate"() {
        given: "generating Ids and persistence is fine"
        def employee = createEmployee()
        employee.id == null
        employee.getDepartment().id == null
        def freshEmployee = employeeRepository.save(employee)
        println(freshEmployee)

        when:
        def jEmployee = createEmployee()
        def jFreshEmployee = employeeRepositoryWithJavers.save(jEmployee)
        println(jFreshEmployee)

        then:
        javers.findSnapshots(byInstanceId(jFreshEmployee.id, EmployeeEntity).build()).size() == 1
        javers.findSnapshots(byInstanceId(jFreshEmployee.department.id, DepartmentEntity).build()).size() == 1
    }

    EmployeeEntity createEmployee() {
        DepartmentEntity departmentEntity = new DepartmentEntity(id:UUID.randomUUID())
        EmployeeEntity employeeEntity = new EmployeeEntity()
        employeeEntity.setId(UUID.randomUUID())
        employeeEntity.setDepartment(departmentEntity)
        employeeEntity
    }
}